﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Newtonsoft.Json;
using System.IO;

namespace ProgramCat.FiddlerExtension.Core.JsonEditor
{
    public partial class JsonEditor : UserControl
    {
        private string tempJson = "";
        public JsonEditor()
        {
            InitializeComponent();
            jsonView.OnAfterSelect += OnAfterSelect;
        }
        /// <summary>
        /// json格式化
        /// </summary>
        /// <param name="json"></param>
        /// <returns></returns>
        public string JsonFormat(string json) {
            try
            {
                JsonSerializer s = new JsonSerializer();
                JsonReader reader = new JsonTextReader(new StringReader(json));
                Object jsonObject = s.Deserialize(reader);
                if (jsonObject != null)
                {
                    StringWriter sWriter = new StringWriter();
                    JsonTextWriter writer = new JsonTextWriter(sWriter);
                    writer.Formatting = Formatting.Indented;
                    writer.Indentation = 4;
                    writer.IndentChar = ' ';
                    s.Serialize(writer, jsonObject);
                    return  sWriter.ToString();
                }
            }
            catch 
            {
                
            }
            return "";
        }

        /// <summary>
        /// 刷新json到 树试图
        /// </summary>
        /// <param name="json"></param>
        public void Json2Tree(string json)
        {
            if (tempJson == json)
                return;
            tempJson = json;
            jsonView.Json = json;
            
        }
        private void OnAfterSelect(JsonViewerTreeNode value)
        {
            jsonNodePathTextBox.Text = value.GetNodePath();
    
        }

        private void json2Tree_Click(object sender, EventArgs e)
        {
            Json2Tree(jsonTextBox.Text);
        }

        private void FormaButton_Click(object sender, EventArgs e)
        {
            jsonTextBox.Text = JsonFormat(jsonTextBox.Text);
        }

        private void expandAllButton_Click(object sender, EventArgs e)
        {
            jsonView.ExpandAll();
        }

        private void collapseAllButton_Click(object sender, EventArgs e)
        {
            jsonView.CollapseAll();
        }
    }
}
